<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class MapNationalStreetModel extends BaseModel
{
    protected $table = "map_national_streets";

    protected $fillable = [
        'wgNumber',
        'name',
        'status',
        'grade',
        'province',
        'city',
        'district',
        'address',
        'lat',
        'lng',
        'coords',
        'shopNum',
        'provinceCode',
        'cityCode',
        'districtCode',
    ];

    protected $appends = [
        'coordsArr',
        'nameText',
    ];

    public function getCoordsArrAttribute(): array
    {
        return collect(json_decode($this->coords, true))->map(function ($item) {
            return [
                'lng' => $item[0],
                'lat' => $item[1],
            ];
        })->toArray();
    }

    public function logRel(): HasMany
    {
        return $this->hasMany(OpenShopSiteLocationExamineLogModel::class, 'orderNo', 'wgNumber');
    }


    public function resourceWithMapRel()
    {
        return $this->hasOne(ResourcesModel::class, 'name', 'wgNumber')->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)->where('business', ResourcesModel::BUSINESS_WG_AUDIT);
    }

    /**
     * 定义一个修改器
     * @return mixed
     */
    public function getNameTextAttribute()
    {
        if (mb_strpos($this->address, $this->name) === false) {
            $name = $this->name;
        } else {
            $name = mb_substr($this->address, mb_strpos($this->address, $this->name));
        }
        return $name;
    }


    /**
     * 关联大客户部选址任务
     * @return HasOne
     */
    public function siteTaskRel(): HasOne
    {
        return $this->hasOne(CustomerDepartmentTaskModel::class, 'wgNumber', 'wgNumber');
    }
}
